<script setup lang="ts">
import {nextTick, onMounted, ref} from 'vue';
import {Image as VanImage, Toast} from 'vant';
import router from "@/router";
import {getChatList} from "@/api/chat";
import {useUserStore} from "@/store/user";

const ws = new WebSocket('ws://localhost:8123/api/chat/public');
ws.onopen = function () {
  console.log('WebSocket 连接已经建立。');
};
ws.onmessage = function (event) {
  console.log('收到服务器消息：', event.data);
  const parse = JSON.parse(event.data);
  parse.isSelf = parse.fromId === user.id;
  messages.value.push(parse);
};
ws.onerror = function (event) {
  console.error('WebSocket 连接出现错误：', event);
};
ws.onclose = function () {
  console.log('WebSocket 连接已经关闭。');
};

interface Message {
  fromId: number;
  nickname: string;
  avatar: string | null;  // 头像可能为null
  text: string;
  createTime: string;     // ISO格式时间 "2025-07-24T12:56:59.000+00:00"
  isSelf: boolean;
}

// 模拟消息数据
// const messages = ref([
//   {
//     nickname: 'jorsi',
//     avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
//     content: '感觉还可以',
//     time: '2025年05月12日10:38:13',
//     isSelf: false
//   },
//   {
//     nickname: 'jorsi',
//     avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/dog.jpeg',
//     content: '你们是在哪个地区的',
//     time: '2025年05月12日10:38:41',
//     isSelf: false
//   },
//   {
//     nickname: 'dada',
//     avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/logo.png',
//     content: '有人在吗????',
//     time: '2025年05月12日16:18:26',
//     isSelf: false
//   },
//   {
//     nickname: 'sysadmin',
//     avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/frog.jpeg',
//     content: '哈喽',
//     time: '2025年07月15日03:32:08',
//     isSelf: false
//   },
//   {
//     nickname: '我',
//     avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/avatar.png',
//     content: 'hi',
//     time: '2025年07月15日03:32:15',
//     isSelf: true
//   }
// ]);

const inputMessage = ref('');
const messages = ref<Message[]>([])
const user = useUserStore()

onMounted(async () => {
  messages.value = await getChatList()
  messages.value.map(msg => {
    msg.isSelf = (msg.fromId === user.id)
  })
  // console.log("res",res)
  // console.log("message",message.value)
})

const sendMessage = () => {
  if (!inputMessage.value.trim()) {
    return;
  }
  const message = {
    fromId: user.id,
    text: inputMessage.value,
    chatType: 2
  }
  ws.send(JSON.stringify( message))
};
</script>

<template>
  <div class="chat-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
        :title="$route.name"
        left-arrow
        @click-left="router.back()"
    />

    <!-- 聊天内容区域 -->
    <div class="chat-content">
      <!-- 消息列表 -->
      <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-item', message.isSelf ? 'self' : 'other']"
      >
        <!-- 他人消息 -->
        <div v-if="!message.isSelf" class="other-message">
          <van-image
              width="40"
              height="40"
              :src="message.avatar"
              class="avatar"
          />
          <div class="message-content">
            <div class="message-info">
              <span class="nickname">{{ message.nickname }}</span>
              <span class="time">{{ message.createTime }}</span>
            </div>
            <div class="message-bubble">{{ message.text }}</div>
          </div>
        </div>

        <!-- 自己消息 -->
        <div v-else class="self-message">
          <div class="message-content">
            <div class="message-info">
              <span class="time">{{ message.createTime }}</span>
            </div>
            <div class="message-bubble">{{ message.text }}</div>
          </div>
          <van-image
              width="40"
              height="40"
              :src="message.avatar"
              class="avatar"
          />
        </div>
      </div>
    </div>

    <!-- 底部输入框 -->
    <div class="chat-input">
      <van-field
          v-model="inputMessage"
          placeholder="聊点什么吧..."
          class="input-field"
      />
      <van-button type="primary" class="send-btn" @click="sendMessage">发送</van-button>
    </div>
  </div>
</template>


<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.chat-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.message-item {
  margin-bottom: 15px;
}

.other-message {
  display: flex;
  justify-content: flex-start;
}

.self-message {
  display: flex;
  justify-content: flex-end;
}

.avatar {
  border-radius: 50%;
  margin: 0 10px;
}

.message-content {
  max-width: 70%;
}

.message-info {
  margin-bottom: 5px;
  font-size: 12px;
  color: #999;
}

.message-info .nickname {
  margin-right: 8px;
}

.message-bubble {
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
}

.other .message-bubble {
  background-color: #f7f8fa;
  color: #333;
}

.self .message-bubble {
  background-color: #1989fa;
  color: #fff;
}

.chat-input {
  display: flex;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #eee;
  background-color: #fff;
}

.input-field {
  flex: 1;
  margin-right: 10px;
  background-color: #f7f8fa;
  border-radius: 18px;
}

.send-btn {
  width: 60px;
  border-radius: 18px;
}
</style>
